import urllib.request
import socket
import ipaddress

def get_ipv6_address():
    urls = [
        "https://ipv6.ident.me",
        "https://ipinfo.io/ip",
        "https://6.ipw.cn"
    ]
    
    for url in urls:
        try:
            response = urllib.request.urlopen(url, timeout=5)
            ip = response.read().decode("utf-8").strip()
            
            # 验证是否为合法IPv6地址
            ipaddress.IPv6Address(ip)
            return ip
            
        except (urllib.error.URLError, socket.timeout):
            continue
        except (ValueError, ipaddress.AddressValueError):
            continue
            
    return None

if __name__ == "__main__":
    ipv6 = get_ipv6_address()
    if ipv6:
        print(f"获取到的IPv6地址: {ipv6}")
    else:
        print("无法获取有效的IPv6地址")
